package loaders
{
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	import flash.utils.Dictionary;

	public class URLResCacher
	{
		private var _loader:URLLoader = null;
		
		private var _cache:Dictionary = null;
		
		public var onLoaded : Function = null;
		public static var onError : Function = null;
		
		private var _url:String = null;
		private var _preload:Boolean = false;
			
		public function URLResCacher()
		{
			_loader = new URLLoader();
			_cache = new Dictionary();

			_loader.dataFormat = URLLoaderDataFormat.BINARY;
			_loader.addEventListener(Event.COMPLETE,_onLoadComplete);
			_loader.addEventListener(IOErrorEvent.IO_ERROR, _onIOError);
		}
		
		public function load( url:String, preload:Boolean = false ):void
		{
			_url = url;
			_preload = preload;
			
			if ( _cache[_url] != null )
			{
				if ( !_preload && onLoaded != null )
				{
					onLoaded(  _cache[_url] );
				}
			}
			else
			{
				var physicalURL:String = ResCacher.getInstance().resourceRoot + url;
				
				_loader.load(new URLRequest(physicalURL));
			}
		}
		
		private function _onLoadComplete( e : Event ):void
		{
			var tmploader:URLLoader = e.currentTarget as URLLoader;
			
			_cache[_url] = tmploader.data;
			
			if ( !_preload && onLoaded != null )
			{
				onLoaded( tmploader.data );
			}
		}
		
		private function _onIOError( event : IOErrorEvent ):void
		{
			if ( onError != null )
			{
				onError( _url, event );
			}
		}
	}
}